package core.game;

import core.board.Action;
import core.board.Board;
import core.player.Player;
import core.player.SocketDelegate;
import dao.IGameInfoDao;
import dao.impl.GameInfoImpl;
import entity.GameInfo;

import static core.board.PieceColor.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.swing.JOptionPane;

public class Referee {

	private Board _board;
	private Player _black, _white;
	private String endReason; // 棋局结束的原因; F 正常结束；T 超时；
								// E 棋手内部错误；N 非法走步；M 超过最大步数
	private int steps = 0; // 棋局下了多少步
	private Connect6Rule _rule;
	private GameInfo game;
	// 某点四个前进方向的位移量；后退方向 = -前进方向
	// 前进方向：下， 右，右下，右上； {col增量，row增量}

	public static final int FORWARD[][] = { { 0, 1 }, { 1, 0 }, { 1, 1 }, { 1, -1 } };

	public Referee(Player black, Player white) {
		_board = new Board();
		_board.clear();
		_black = black;
		_white = white;
		_rule = new Connect6Rule(_board);
	}

	// 轮到谁下棋
	public Player whoseMove() {
		return _board.whoseMove() == WHITE ? _white : _black;
	}

	// 棋局是否结束
	public boolean gameOver() {
		return _board.gameOver();
	}

	// 处理异常
	public void endingGame(String endReason, Player currPlayer, Move currMove) {
		System.out.println("=====endingGame=========");
		_black.stopTimer();
		_white.stopTimer();
		if (currPlayer instanceof SocketDelegate) {
			((SocketDelegate) currPlayer).sendMove(currMove);
		}
		// F 正常结束；T 超时；E 棋手内部错误；N 非法走步；M 超过最大步数（平局）
		String gameResult = "";
		switch (endReason) {
		case "F":
			gameResult = "Success:" + getWinner();
			break;
		case "T":
			gameResult = currPlayer.name() + "Overtime";
			break;
		case "E":
			gameResult = currPlayer.name() + "Chess player internal error";
			break;
		case "N":
			gameResult = currPlayer.name() + "Illegal walking";
			break;
		case "M":
			gameResult = "It ends in a draw";
			break;
		default:
			break;
		}
		this.endReason = gameResult;
		// this.endReason = endReason;
		recordGame();
	}

	// 是否合法走步
	public boolean legalMove(Move mov) {
		return _rule.legalMove(mov);
	}

	// 记录走步
	public void recordMove(Move move) {
		System.out.println("======MOVE=====");
		// TODO Auto-generated method stub
		// 对Move进行解析
//		_board.doActions(getActions(move));
		 _board.makeMove(move);
		steps++;
	}

	// 对Move进行解析
	public List<Action> getActions(Move move) {
		List<Action> actions = new ArrayList<>();
		actions.add(new Action(move.col0(), move.row0(), _board, "SET"));
		actions.add(new Action(move.col1(), move.row1(), _board, "SET"));
		return actions;
	}

	// 为黑白双方生成棋局报告
	public void recordGame() {
		System.out.println("========recordGame=======");
		GameResult result = new GameResult(_black.name(), _white.name(), getWinner(), steps, endReason);
		System.out.println(result.toString());
		// 添加到黑棋和白棋的对局结果列表
		_black.addGameResult(result);
		_white.addGameResult(result);

		// 将对战结果存储到数据库中
		game = new GameInfo();
		game.setBlackName(_black.name());
		game.setWhiteName(_white.name());
		game.setWinerName(getWinner());
		game.setStep(steps);
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		game.setDate(dateFormat.format(new Date()));
		// 获取走步
		Iterator<Move> itr = _board.getMoveList().iterator();
		String moveString = "";
		while (itr.hasNext()) {
			moveString += itr.next().toString() + ",";
		}
		game.setResult(moveString);
		game.setReason(this.endReason);
		_board.showMoves();
		IGameInfoDao gameInfo = new GameInfoImpl();
		gameInfo.saveGameResult(game);

	}

	private String getWinner() {

		// 如果是超过最大步数而结束，
		if ("M".equalsIgnoreCase(endReason)) {
			return "NONE";
		}

		// // 如果是超时负，
		// if ("T".equalsIgnoreCase(endReason)) {
		// //轮到下棋的那一方，判定为赢家。即，轮到白棋下，则白胜
		// return _board.whoseMove() == WHITE ? _white.name() : _black.name();
		// }

		// 轮到下棋的那一方，判定为输家。即，轮到白棋下，则黑胜，否则，白胜
		return _board.whoseMove() == WHITE ? _black.name() : _white.name();
	}
}
